package com.clayecloud.common.utils;

import cn.hutool.crypto.asymmetric.RSA;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Component
public class JJWTUtil {

    //获取密钥
    private static RSA rsa;

    static {
        try {
            rsa = new RSA(RSAUtil.getKeyFromFile("key.pri"),RSAUtil.getKeyFromFile("key.pub"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生产token
     */
    public static String createToken(Map map,Long time) {
        Date now = new Date();
        return Jwts.builder()
                .setClaims(map)
                .setIssuedAt(now)
                .setExpiration(new Date(now.getTime() + time))
                .signWith(rsa.getPrivateKey())
                .compact();
    }

    /**
     * 验证token
     */
    public static Boolean verifyToken(String token) {
        try {

            Jwts.parserBuilder().setSigningKey(rsa.getPublicKey()).build().parseClaimsJws(token);
            //OK, we can trust this JWT
            return true;

        } catch (JwtException e) {
            //don't trust the JWT!
            return false;
        }
    }

    /**
     * 获取token中的Claims
     */
    public static Claims getClaims(String token){
        Jws<Claims> jws;
        jws = Jwts.parserBuilder()
                .setSigningKey(rsa.getPublicKey())
                .build()
                .parseClaimsJws(token);
        return jws.getBody();
    }


}
